import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 根据当前用户请求中的 sessionId, 获取到用户信息,并显示到页面上
        resp.setContentType("text/html;charset=utf-8");
        // 1. 判定当前用户是否已经登录了.
        HttpSession httpSession = req.getSession(false);//这里如果不存在就不需要创建.
        if (httpSession == null) {
            resp.sendRedirect("login.html");
            return;
        }
        // 2. 如果已经登录,就可以从 HttpSession 中拿到用户信息了
        String username = (String) (httpSession.getAttribute("username"));
        Integer loginCount = (Integer) (httpSession.getAttribute("loginCount"));
        loginCount = loginCount + 1;
        httpSession.setAttribute("loginCount", loginCount);
        // 3. 返回一个 HTML 页面
        StringBuilder html = new StringBuilder();
        html.append("<div>用户: " + username + "</div>");
        html.append("<div>访问次数: " + loginCount + "</div>");
        resp.getWriter().write(html.toString());
    }
}
